package net.lico;


import java.io.*;
import java.util.*;

/**
 * 将键道Rime词库转成可以挂载手心、搜狗的txt词库文件
 */
public class RimeDict2PalmInput {

//    private final static String path = System.getProperty("user.dir");
//    private static final List<String> feiList = Arrays.asList(/*"em",*/"qk",
//        "fp","ff","fh","fz","fr","fn","fw","fj",
//        "jp","jf","jh","jz","jr","jn","jw","jj");
    
    private static final List<String> deleteFeiList = Arrays.asList("wm","km","hm","gm","fm","em");
            
    //wm - wx
    //km - kx
    //hm - hx
    //gm - gx
    //fm - fx
    //em - ex
    public static void main(String[] args) {
//        yd("dict-palminput.txt");
//        yb("dict-palminput.txt");
        jd6("dict-palminput-20.0907.txt");
        System.out.println("完事");
    }
    private static void yd(String fileName){
        //        System.out.println(path);
        String path = "G:\\soft\\viewer&editor\\input\\一道\\星空一笔道0911\\";
//        String path = "D:\\一道\\星空一笔道(一道点儿词库)0412_sign\\";
//        String path = "D:\\一道\\星空一道歌颂终结版\\rime\\";
        Map<String, Map<Integer, String>> map = new HashMap<String, Map<Integer, String>>();
        //编码, 次数(序号) - 汉字
        File fileDZ5 = new File(path + "/xkyddz.dict.yaml");
        putMapFromDictFile(map, fileDZ5);
//        File fileDZ4 = new File(path + "/xkydcz.dict.yaml");
//        putMapFromDictFile(map, fileDZ4);
//        File fileDZ4 = new File(path + "/xkydcz_de.dict.yaml");
//        putMapFromDictFile(map, fileDZ4);
        //单字
        File fileDZ1 = new File(path + "/xkydbc.dict.yaml");
        putMapFromDictFile(map, fileDZ1);
        File fileDZ2 = new File(path + "/xkydbd.dict.yaml");
        putMapFromDictFile(map, fileDZ2);
        File fileDZ3 = new File(path + "/xkydcj.dict.yaml");
        putMapFromDictFile(map, fileDZ3);
        File fileDZ6 = new File(path + "/xkydfh.dict.yaml");
        putMapFromDictFile(map, fileDZ6);
        File fileDZ7 = new File(path + "/xkydjm.dict.yaml");
        putMapFromDictFile(map, fileDZ7);
//        File fileDZ8 = new File(path + "/xkydlj.dict.yaml");
//        putMapFromDictFile(map, fileDZ8);
//        File fileDZ9 = new File(path + "/xkydyw.dict.yaml");
//        putMapFromDictFile(map, fileDZ9);
        

        writeFullDictFile(path ,fileName , map);
    }
    private static void yb(String fileName){
        //        System.out.println(path);
        String path = "G:\\soft\\viewer&editor\\input\\一笔\\rime\\";
        Map<String, Map<Integer, String>> map = new HashMap<String, Map<Integer, String>>();
        //编码, 次数(序号) - 汉字
        File fileDZ5 = new File(path + "/xkybdz.dict.yaml");
        putMapFromDictFile(map, fileDZ5);
        File fileDZ4 = new File(path + "/xkybcz.dict.yaml");
        putMapFromDictFile(map, fileDZ4);
        //单字
        File fileDZ1 = new File(path + "/xkybbc.dict.yaml");
        putMapFromDictFile(map, fileDZ1);
        File fileDZ2 = new File(path + "/xkybbd.dict.yaml");
        putMapFromDictFile(map, fileDZ2);
        File fileDZ3 = new File(path + "/xkybcj.dict.yaml");
        putMapFromDictFile(map, fileDZ3);


        writeFullDictFile(path ,fileName , map);
    }
    private static void jd6(String fileName ){
        //        System.out.println(path);
        String path = "D:\\app\\Rime_JD\\rime\\";
        String pathExtended = "D:\\app\\Rime_JD\\Tools\\Extended\\";
        //编码, 次数(序号) - 汉字
        Map<String, Map<Integer, String>> map = new HashMap<String, Map<Integer, String>>();
        //单字
        File fileDZ = new File(path + "/xkjd6.danzi.dict.yaml");
        putMapFromDictFile(map, fileDZ);
        //sys
        File filesys = new File(pathExtended + "/xkjd6.sys.dict.yaml");
        putMapFromDictFile(map, filesys);
        //词组
        File fileCZ = new File(path + "/xkjd6.cizu.dict.yaml");
        putMapFromDictFile(map, fileCZ);
        //补充
        File fileBC = new File(path + "/xkjd6.buchong.dict.yaml");
        putMapFromDictFile(map, fileBC);
        //自定义
        File fileZDY = new File(path + "/xkjd6.user.dict.yaml");
        putMapFromDictFile(map, fileZDY);
        //630
//        File file630 = new File(path + "/xkjd6.wxw.dict.yaml");
//        putMapFromDictFile(map, file630);

        writeFullDictFile(path,fileName, map);
    }

    private static void writeFullDictFile(String path,String fileName ,Map<String, Map<Integer, String>> map) {
        Set<String> keySet = map.keySet();
        Iterator<String> iter = keySet.iterator();
//		bi,1=不但
//		bi,2=拜拜
        File dictFile = new File(path + fileName);
        BufferedWriter writer = null;
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(dictFile);
            OutputStreamWriter OSW = new OutputStreamWriter(fileOutputStream, "UTF-8");
//            OutputStreamWriter OSW = new OutputStreamWriter(fileOutputStream, "GBK");
//            OutputStreamWriter OSW = new OutputStreamWriter(fileOutputStream, Charset.availableCharsets().get("UTF-16LE"));//手心编码
            writer = new BufferedWriter(OSW);
            boolean first = true;
            while (iter.hasNext()) {
                String code = iter.next();
                Map<Integer, String> orderMap = map.get(code);
                Set<Integer> integers = orderMap.keySet();
                Iterator<Integer> orderKeys = integers.iterator();
                while (orderKeys.hasNext()) {
                    Integer order = orderKeys.next();
                    String chineseChar = orderMap.get(order);
                    if (first) {
                        first = false;
                    } else {
                        writer.newLine();
                    }
					writer.write(code+","+order+"="+chineseChar);//搜狗
//					writer.write(code+" "+chineseChar+" "+order);//qq
//					writer.write(order+","+code+"="+chineseChar);//4,zuo=← 百度
//					writer.write(code+"="+order+","+chineseChar);//4,zuo=← 百度手机
//                    writer.write(code + "=" + order + "," + chineseChar);//dnf=3,地下城与勇士 手心
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }

    private static void putMapFromDictFile(Map<String, Map<Integer, String>> map, File file) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(file));
            String line = null;
            //中文字词，编码
            Map<String,String> repeatMap = new HashMap<String, String>();
            while ((line = reader.readLine()) != null) {
                int indexTab = line.lastIndexOf("\t");
                if (indexTab == -1) continue;
                String chineseChar = line.substring(0, line.lastIndexOf("\t"));
                if (chineseChar != null && "".equals(chineseChar.trim())) continue;
                chineseChar = chineseChar.trim();
                String code = line.substring(line.lastIndexOf("\t"), line.length());
                if (code != null && "".equals((code.trim()))) continue;
                code = code.trim();
//                if(filterCode(repeatMap,chineseChar,code)) {
//                    if (chineseChar.length() <= 2) {
//                        String addedCode = repeatMap.get(chineseChar);
////                        System.out.println(chineseChar + " 存在重复编码, new：" + code + " , addedCode: " + addedCode);
//                    }
//                    continue;
//                }
                Map<Integer, String> orderMap = map.get(code);
                if (orderMap == null) {
                    orderMap = new HashMap<Integer, String>();
                    map.put(code, orderMap);
                }
                Set<Integer> integers = orderMap.keySet();
                if (integers.size() == 0) {
                    orderMap.put(1, chineseChar);
                } else {
                    Integer maxIndex = null;
                    //出现同一个编码，同一个词组的重复
                    Iterator<String> iterator = orderMap.values().iterator();
                    boolean isRepeate = false;
                    while (iterator.hasNext()){
                        String next = iterator.next();
                        if(chineseChar.equals(next)){
                            isRepeate = true;
                            break;
                        }
                    }
                    if(isRepeate){
                        continue;
                    }
                    Iterator<Integer> indexIter = integers.iterator();
                    
                    while (indexIter.hasNext()) {
                        Integer idx = indexIter.next();
                        if (maxIndex == null) {
                            maxIndex = idx;
                            continue;
                        }
                        if (idx > maxIndex) {
                            maxIndex = idx;
                        }
                    }
                    orderMap.put(maxIndex + 1, chineseChar);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    /**
     * 
     * @param repeatMap
     * @param chineseChar
     * @param code
     * @return true 需要过滤，false 不用过滤
     */
    private static boolean filterCode(Map<String,String> repeatMap,String chineseChar,String code){
        if (chineseChar.length() > 2) {//去除多字词，只保留双字词组
//                    System.out.println(chineseChar+" --");
            return true;
        }
        //判断一下是不是前两位一样的，可以区分全码跟简码
//        String addedCode = repeatMap.get(chineseChar);
//        if (addedCode == null) {
//            repeatMap.put(chineseChar, code);
//        } else {
            boolean fei = false;
            if(code.length()>1){
                if(code.length()<=3) {
                    for (String deleteFei : deleteFeiList) {
                        if (code.startsWith(deleteFei)) {
                            fei = true;
                            System.out.println(deleteFei);
                            break;
                        }
                    }
//                    if (code.startsWith("em")) {
//                        fei = true;
//                    }
//                    if(startCodeInList(code)){
//                        fei = true;
//                    }
                }else{
                    String firstCode = code.substring(0, 2);
                    String secondCode = code.substring(2,code.length());
                    for (String deleteFei : deleteFeiList) {
                        if (code.startsWith(deleteFei) || secondCode.startsWith(deleteFei)) {
                            fei = true;
                            break;
                        }
                    }
//                    if(firstCode.startsWith("em")){
//                        fei = true;
//                    }
//                    if(secondCode.startsWith("em")){
//                        fei = true;
//                    }
//                    if(startCodeInList(firstCode)){
//                        fei = true;
//                    }
//                    if(startCodeInList(firstCode)){
//                        fei = true;
//                    }

                }
            }
//            for (String s : feiList) {
//                if(code.startsWith(s)){
//                    fei = true;
//                    break;
//                }
//
//            }
            if(fei)return true;

//            if (code.length() >= addedCode.length()) {//只保留简码
//                return true;
//            }
//        }
        return false;
    }
    private static boolean startCodeInList(String code){
        boolean fei = false;
//        for (String s : feiList) {
//            if(code.startsWith(s)){
//                fei = true;
//                break;
//            }
//
//        }
        return fei;
    }
    
}
